package com.eternal.weChat.mp.controller;/**
 * @Title: Mpcontroller
 * @ProjectName notest
 * @Description: TODO
 * @author Eternal
 * @date 2018/11/28 22:07
 */

import com.eternal.Exception.ResultEnum;
import com.eternal.Exception.ResultVo;
import com.eternal.util.user.entity.UserInfo;
import com.eternal.util.user.service.UserInfoService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.menu.WxMenu;
import me.chanjar.weixin.common.bean.menu.WxMenuButton;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.menu.WxMpMenu;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Class Mpcontroller
 * @Description: TODO
 * @Author Eternal
 * @Version
 * @date 2018/11/28 22:07
 */
@Controller
@RequestMapping("/wechatMp")
@Slf4j
public class Mpcontroller {

    @Autowired
    private WxMpService wxMpService;

    @Autowired
    private UserInfoService userInfoService;

    @GetMapping("/init")
    public void init(String signature, String timestamp, String nonce, String echostr, HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter writer = response.getWriter();
        log.info("signature:{},timestamp:{},nonce:{},echostr:{}", signature, timestamp, nonce, echostr);

        StringBuffer json = new StringBuffer();
        String lineString = null;
        try {
            BufferedReader reader = request.getReader();
            while ((lineString = reader.readLine()) != null) {
                json.append(lineString);
            }
        } catch (Exception e) {
            System.out.println(e.toString());
        }

        if (wxMpService.checkSignature(timestamp, nonce, signature)) {
            writer.print(echostr);
        }
    }

    @PostMapping("/init")
    public void init(HttpServletRequest request, HttpServletResponse response) throws IOException {


        response.setContentType("text/html;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);

        System.out.println(request.getParameter("encrypt_type"));

        WxMpXmlMessage wxMpXmlMessage = WxMpXmlMessage.fromXml(request.getInputStream());
        System.out.println(wxMpXmlMessage);
       /* String encryptType = StringUtils.isBlank(request.getParameter("encrypt_type")) ?
                "raw" :
                request.getParameter("encrypt_type");

        WxMpXmlMessage inMessage = null;

        if ("raw".equals(encryptType)) {
            // 明文传输的消息
            inMessage = WxMpXmlMessage.fromXml(request.getInputStream());
        } else if ("aes".equals(encryptType)) {
            // 是aes加密的消息
            String msgSignature = request.getParameter("msg_signature");
            inMessage = WxMpXmlMessage.fromEncryptedXml(request.getInputStream(), wxMpConfigStorage, timestamp, nonce, msgSignature);
        } else {
            response.getWriter().println("不可识别的加密类型");
            return;
        }

        WxMpXmlOutMessage outMessage = wxMpMessageRouter.route(inMessage);

        if (outMessage != null) {
            if ("raw".equals(encryptType)) {
                response.getWriter().write(outMessage.toXml());
            } else if ("aes".equals(encryptType)) {
                response.getWriter().write(outMessage.toEncryptedXml(wxMpConfigStorage));
            }
            return;*/
    }

    @GetMapping("/menu")
    @ResponseBody
    public void menu() {
        List<WxMenuButton> btnMenus = new ArrayList<>();

        WxMenuButton wxMenuButton = new WxMenuButton();
        wxMenuButton.setType("view");
        wxMenuButton.setName("点餐");
        wxMenuButton.setKey("diancan");
        wxMenuButton.setUrl("http://eternal.nat100.top/#/weChatIndex");
        btnMenus.add(wxMenuButton);
        WxMenuButton wxMenuButton1 = new WxMenuButton();

        wxMenuButton1.setType("view");
        wxMenuButton1.setName("我的");
        wxMenuButton1.setKey("my");
        wxMenuButton1.setUrl("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx281e7d59de450db4&redirect_uri=http%3a%2f%2feternal.nat100.top%2f%23%2fweChatLogin&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");

        btnMenus.add(wxMenuButton1);

        WxMenu wxMenu = new WxMenu();
// 设置菜单
        wxMenu.setButtons(btnMenus);
        try {
            wxMpService.getMenuService().menuCreate(wxMenu);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/queryMenu")
    @ResponseBody
    public ResultVo queryMenu() {
        try {
            WxMpMenu wxMpMenu = wxMpService.getMenuService().menuGet();
            return new ResultVo(wxMpMenu);
        } catch (WxErrorException e) {
            e.printStackTrace();
            return new ResultVo<>(e);
        }
    }

    @GetMapping("/queryWechatinfo")
    @ResponseBody
    public ResultVo queryWechatinfo(String openId) {
        try {
            WxMpUser wxMpMenu = wxMpService.getUserService().userInfo(openId);
            return new ResultVo(wxMpMenu);
        } catch (WxErrorException e) {
            e.printStackTrace();
            return new ResultVo<>(e);
        }
    }

    @GetMapping("/getOpenId")
    @ResponseBody
    public ResultVo<Map<String, Object>> getOpenId(String code) {
        try {
            WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
            UserInfo userInfoByopenId = userInfoService.getUserInfoByopenId(wxMpOAuth2AccessToken.getOpenId());
            Map<String, Object> map = new HashMap<>();
            map.put("token", wxMpOAuth2AccessToken);
            map.put("userinfo", userInfoByopenId);
            WxMpUser wxMpMenu = wxMpService.getUserService().userInfo(wxMpOAuth2AccessToken.getOpenId());
            map.put("wechatinfo", wxMpMenu);
            return new ResultVo(map);
        } catch (WxErrorException e) {
            e.printStackTrace();
            return new ResultVo(ResultEnum.ERROR, e);
        }

    }
}
